<?php

namespace Ffzhou\HydrophisLogin\Listener;

use Ffzhou\HydrophisLogin\Extend\FieldFlint;
use Ffzhou\HydrophisLogin\Extend\SwooleClient;
use Flarum\Http\UrlGenerator;
use Flarum\Post\Event\Posted;
use Flarum\Settings\SettingsRepositoryInterface;

/**
 * 发送Mqtt，通知该主题有新的回复
 * Class PostedMqtt
 * @package Ffzhou\HydrophisLogin\Listener
 */
class PostedListen
{
    /**
     * @var SettingsRepositoryInterface
     */
    protected $settings;
    /**
     * @var Posted
     */
    protected $event;
    /**
     * @var UrlGenerator
     */
    protected $url;

    public function __construct(SettingsRepositoryInterface $settings, UrlGenerator $url)
    {
        $this->settings = $settings;
        $this->url = $url;
    }

    final public function handle(Posted $event): void
    {
        $this->event = $event;
        $this->sendMqtt();
    }

    /**
     * 发送mqtt通知
     * @return bool
     */
    protected function sendMqtt() {
        // 判断是否启动mqtt
        $enable = $this->settings->get('ffzhou-hydrophis-login.mqtt_enable');
        if (!$enable) {
            return false;
        }
        // 获取对应讨论主题的发起人
        $post = $this->event->post;
        $discussion = $post->discussion;
        $user = $discussion->user;
        if ($user->id === $post->user_id) {
            return false;
        }

        // 讨论标题和回复内容
        $title = $discussion->title;
        $content = strip_tags($post->content);
        $path = 'd/'. $post->discussion->id . ($discussion->slug ? '-'.$discussion->slug : '');
        $url = $this->url->to('forum')->path($path);

        // 获取发起人第三方身份ID
        $provider = $user->loginProviders
            ->where('provider', FieldFlint::LOGIN_PROVIDER)
            ->first();
        if (empty($provider)) {
            return false;
        }
        $identifier = $provider->identifier;

        // 向mqtt发送通知
        // 获取Swoole服务器Url和端口
        $server = $this->settings->get('ffzhou-hydrophis-login.mqtt_swoole_server');
        $serverPort = $this->settings->get('ffzhou-hydrophis-login.mqtt_swoole_server_port');
        if (empty($server)) {
            return false;
        }

        // 连接Swoole服务器Url发送通知
        $swooleType = 1;
        $topic = '@/user/'. $identifier .'/bbs/posted';
        $msg = compact('title', 'content', 'url');
        $result = SwooleClient::instance()->setConfig($server, $serverPort)
            ->publish(compact('swooleType', 'topic', 'msg'));
        return $result;
    }
}
